package net.wanho.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import net.wanho.properties.JwtProperties;

import java.util.Calendar;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {

    private static final String SECRET;
    private static final int EXPIRE; // 分钟

    static {
        JwtProperties jwtProperties = ApplicationContextHolder.getBean(JwtProperties.class);
        SECRET = jwtProperties.getSecret();
        EXPIRE = jwtProperties.getExpire();
    }

    /**
     * 生成token
     * @param payload
     * @return
     */
    public static String generate(Map<String,Object> payload) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE,EXPIRE);

        String token = JWT.create()
                .withPayload(payload)
                .withExpiresAt(c.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean valid(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (RuntimeException e) {
            throw e;
        }
    }

    /**
     * 解析token
     * @param token
     * @param key
     * @return
     */
    public static Integer parseInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static Long parseLong(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asLong();
    }

    public static String parseString(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }

    /**
     * 反码token
     * @param token
     * @param key
     * @return
     */
    public static Integer decodeInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static Long decodeLong(String token, String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asLong();
    }

    public static String decodeString(String token, String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asString();
    }

}
